package com.wl.dzt.basic.service;

import com.wl.dzt.basic.entity.BasicDic;
import com.wl.dzt.basic.entity.BasicModel;
import com.wl.dzt.basic.user.User;
import com.wl.dzt.sys.core.dao.JDao;
import com.wl.dzt.sys.core.dao.select.Select;
import com.wl.dzt.sys.core.dao.select.order.Order;
import com.wl.dzt.sys.core.dao.select.term.Term;
import com.wl.dzt.sys.core.dao.tree.TreeBuilder;
import com.wl.dzt.sys.core.dao.tree.TreeSetting;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/6/14/014
 * @description 系统管理的基础的服务
 */
@Service
public class BasicService {

    @Resource
    private JDao jDao;

    /**
     * 根据权限和角色查询出菜单
     * @param user
     *          用户
     * @return
     */
    public List<Map<String, Object>> modelList(User user) {
        // 管理员逻辑
        List<Term> wheres = new ArrayList<>();

        if (user != null && !user.isAdmin()) {
            // 可能存在 in 过长问题
            wheres.add(Term.in("id", user.getAttr("modelIds").toString().split(",")));
        }
        List<BasicModel> basicModels = jDao.list(Select.create(BasicModel.class).where().order(Order.asc("modelSort"))
                .where(wheres.toArray(new Term[wheres.size()])).fields("modelParentId.id"));
        List<Map<String, Object>> data = TreeBuilder.cascadeTree(basicModels,
                TreeSetting.createByExp("id,modelName,modelParentId.id,modelIcon,modelJs,modelMain"));
        return data;
    }

    /**
     * 查询出所有的字典
     *
     * @return
     */
    public Map<String, List<Map<String, Object>>> dicList() {
        List<BasicDic> basicDics = jDao.list(Select.create(BasicDic.class).order(Order.asc("dicSort")).fields("dicParentId.dicValue")
                .where(Term.eq("dicState", "1")));
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        basicDics.stream().filter(dic -> dic.getDicType().equals("1"))
                .forEach(dic -> map.put(dic.getDicValue(), new ArrayList<Map<String, Object>>()));
        basicDics.stream().filter(dic -> !dic.getDicType().equals("1")).forEach(dic -> {
            if (dic.getDicParentId() != null) {
                List<Map<String, Object>> list = map.get(dic.getDicParentId().getDicValue());
                if (list != null) {
                    Map<String, Object> dicInfo = new HashMap<String, Object>();
                    dicInfo.put("value", dic.getDicValue());
                    dicInfo.put("text", dic.getDicKey());
                    dicInfo.put("sort", dic.getDicSort());
                    list.add(dicInfo);
                }
            }
        });
        return map;
    }
}
